select count(1) 、select count(*) 、select count(字段)的区别、及性能 您所在的位置:网站首页 inner room什么意思 select count(1) 、select count(*) 、select count(字段)的区别、及性能

select count(1) 、select count(*) 、select count(字段)的区别、及性能

#select count(1) 、select count(*) 、select count(字段)的区别、及性能| 来源: 网络整理| 查看: 265

select count(*) from teacher; //11 select count(1) from teacher;  //11 select count(id) from teacher;  //8 不包含null列,但是包含空字符串列 select count(name) from teacher;  //10 select count(address) from teacher; //11 结论:

select 1 和select *

select * from 表;查询出表中所有数据,性能比较差;

select 常量 from 表;查询出结果是所有记录数的常量,性能比较高;

selelct 常量 from ... 对应所有行,返回的永远只有一个值,即常量。例如 select 1 from 表名 。。。

所以正常只会用来判断是否有还是没有(比如exists子句)。而select * from ... 是返回所有行的所有列。

如果要判断是否有结果使用select 1,如果要返回数据,使用select * ;

Select Count (*)和Select Count(1)和select Count(字段)

一般情况下,Select Count (*)和Select Count(1)两着返回结果是一样的

如果表中没有主键 ,使用count(1)比count(*)快;

如果有主键,那么count(主键)最快

count(*)和count(1)的结果一样,都包括对NULL的统计,而count(字段) 不包括NULL的统计;

实操中,选择使用 count(1)的情况比较多;

总结:

只要存在普通索引,count就会使用普通索引,

只存在主键时,count(*)和或count(1)会使用主键索引,其他字段不会

count(*)和或count(1)最快

实例:SQL查找是否"存在"

目前多数人的写法 业务代码中,需要根据一个或多个条件,查询是否存在记录,不关心有多少条记录。普遍的SQL及代码写法如下

##### SQL写法: SELECT count(*) FROM table WHERE a = 1 AND b = 2 ##### Java写法: int nums = xxDao.countXxxxByXxx(params); if ( nums > 0 ) { //当存在时,执行这里的代码 } else { //当不存在时,执行这里的代码 } 优化方案 ##### SQL写法: SELECT 1 FROM table WHERE a = 1 AND b = 2 LIMIT 1 ##### Java写法: Integer exist = xxDao.existXxxxByXxx(params); if ( exist != NULL ) { //当存在时,执行这里的代码 } else { //当不存在时,执行这里的代码 } 再次优化: SELECT count(1) FROM table WHERE a = 1 AND b = 2 LIMIT 1 SQL不再使用count,而是改用LIMIT 1,让数据库查询时遇到一条就返回,不要再继续查找还有多少条了 业务代码中直接判断是否非空即可



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有